from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

# Create your models here.


class Profile(models.Model):
    # 用户个人资料
    account_type = (("0", "主账号"), ("1", "子账号"),)
    level = ((0, '体验用户'), (1, '付费用户'))

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company = models.CharField(u'公司名称', max_length=255, blank=True, null=False)
    phone = models.CharField(u'手机号', max_length=11, blank=True, null=False)
    last_login_ip = models.CharField(u'最近登录IP', max_length=30, blank=True, null=True)
    avatar = models.CharField(u'头像', max_length=255, blank=True, null=True)
    account_type = models.CharField(u'账号类型', choices=account_type, max_length=1, default='0')
    user_level = models.IntegerField('用户等级', choices=level, default=0)

    class Meta:
        db_table = 'profile'

    def __unicode__(self):
        return u'%s' % self.phone


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
